{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from itertools import zip_longest"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## algorithm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# states\n",
    "p0c0 = 0, {}\n",
    "p1c0 = 1, {}\n",
    "p0c1 = 0, {}\n",
    "p1c1 = 1, {}\n",
    "\n",
    "# transitions between states\n",
    "p0c0[1].update({(0, 0): p0c0, (1, 0): p1c0, (0, 1): p1c0, (1, 1): p0c1})\n",
    "p1c0[1].update({(0, 0): p0c0, (1, 0): p1c0, (0, 1): p1c0, (1, 1): p0c1})\n",
    "p0c1[1].update({(0, 0): p1c0, (1, 0): p0c1, (0, 1): p0c1, (1, 1): p1c1})\n",
    "p1c1[1].update({(0, 0): p1c0, (1, 0): p0c1, (0, 1): p0c1, (1, 1): p1c1})\n",
    "\n",
    "def add(x, y):\n",
    "    x = map(int, reversed(x))\n",
    "    y = map(int, reversed(y))\n",
    "    z = []\n",
    "\n",
    "    # simulate automaton\n",
    "    value, transition = p0c0\n",
    "    for r, s in zip_longest(x, y, fillvalue=0):\n",
    "        value, transition = transition[r, s]\n",
    "        z.append(value)\n",
    "\n",
    "    # handle carry\n",
    "    z.append(transition[0, 0][0])\n",
    "    \n",
    "    return ''.join(map(str, reversed(z)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'10001000111100'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "add('1100100100100', '100100011000')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0b10001000111100'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bin(0b1100100100100 + 0b100100011000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
